import { defineStore } from "pinia";
import type { CompanyInfoData } from "@/api/Home";
import { companyInfo } from "@/api/Home"; // 新增导入
import { store } from "@/store";

export const useCompanyStore = defineStore("company", {
  state: () => ({
    companyInfo: null as CompanyInfoData | null,
    hasFetched: false // 新增：标记是否已获取过数据
  }),
  actions: {
    setCompanyInfo(info: CompanyInfoData) {
      this.companyInfo = info;
      this.hasFetched = true; // 标记为已获取
    },
    // 新增：获取公司信息的方法
    async fetchCompanyInfo() {
      // 如果已经获取过，直接返回
      if (this.hasFetched) {
        return this.companyInfo;
      }
      try {
        const result: CompanyInfoData = await companyInfo();
        this.setCompanyInfo(result);
        return result;
      } catch (error) {
        console.error("获取公司信息失败:", error);
        throw error;
      }
    }
  },
  getters: {
    // 新增：获取公司logo的方法
    headimgurl: state => state.companyInfo?.headimgurl || "",
    enableWithdrawAli: state => state.companyInfo?.enableWithdrawAli || "",
    pcUrl: state => state.companyInfo?.pcUrl || "",
    enableOpenWxshopMarket: state =>
      state.companyInfo?.enableOpenWxshopMarket || "",
    enableOpenAgent: state => state.companyInfo?.enableOpenAgent || ""
  }
});

export function useCompanyStoreHook() {
  return useCompanyStore(store);
}
